package com.waqu.common.utils.other;

import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Map.Entry;

/**
 * @Title WeightRandom.java
 * @Package com.waqu.common.utils.other
 * @author Administrator
 * @date 2015年5月5日 下午7:36:22
 * @version V1.0
 */
public class WeightRandom {

	private static final Random random = new Random();

	public static String calculate(Map<String, Integer> weightMaps) {
		Objects.requireNonNull(weightMaps);
		int[] weightArray = new int[weightMaps.size() + 1];
		String[] tempElementArray = new String[weightMaps.size()];
		int i = 0;
		for (Entry<String, Integer> entry : weightMaps.entrySet()) {
			tempElementArray[i] = entry.getKey();
			weightArray[i + 1] = entry.getValue() + weightArray[i];
			i++;
		}
		int totalWeight = weightArray[weightArray.length - 1];
		if (totalWeight <= 0) {
			return tempElementArray[0];
		}
		int randomNum = random.nextInt(totalWeight);
		int index = half(weightArray, randomNum); // 这里正常不会返回-1的
		return index == -1 ? null : tempElementArray[index];
	}

	private static int half(int[] desArray, int des) {
		int lowIndex = 0, highIndex = desArray.length - 1;
		while (lowIndex <= highIndex) {
			int middle = (lowIndex + highIndex) / 2;
			if (des > desArray[middle] && des <= desArray[middle + 1]) {
				return middle;
			} else if (des < desArray[middle]) {
				highIndex = middle - 1;
			} else {
				lowIndex = middle + 1;
			}
		}
		return -1;
	}

}
